package com.spider.im.common.security;

import com.spider.im.common.security.filter.JwtRequestFilter;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;


@Configuration
public class WebSecurityConfig {

    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Resource
    private JwtRequestFilter jwtRequestFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        try {
            // 配置授权规则
            configureAuthorization(http);

            // 配置 CORS
            //                try {
            //
            //                    corsConfigurer.configurationSource(request -> {
            //                        CorsConfiguration config = new CorsConfiguration();
            //                        // 配置允许的来源（可以根据需求调整）
            //                        config.setAllowedOrigins(Collections.singletonList("*"));
            //                        // 配置允许的HTTP方法
            //                        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
            //                        // 配置允许的头部
            //                        config.setAllowedHeaders(Collections.singletonList("*"));
            //                        // 允许凭据（如Cookie）
            //                        config.setAllowCredentials(true);
            //                        return config;
            //                    });
            //                } catch (Exception e) {
            //                    // 捕获并记录异常，确保程序不会因配置错误而崩溃
            //                    System.err.println("CORS configuration failed: " + e.getMessage());
            //                    throw new RuntimeException("Failed to configure CORS", e);
            //                }
            http.cors(AbstractHttpConfigurer::disable);

            // 配置 CSRF
            //                // 允许 Swagger UI 相关路径忽略 CSRF 检查
            //                csrf.ignoringRequestMatchers("/login","/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**");
            //                // 其他 CSRF 配置可以根据需要进行调整
            //                csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
            http.csrf(AbstractHttpConfigurer::disable);

            // 配置登录和登出规则
            configureLoginAndLogout(http);
            http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
            http.exceptionHandling(exceptionHandling -> exceptionHandling
//                    .authenticationEntryPoint((request, response, authException) ->
//                            response.sendError(401, "Unauthorized"))
                    .accessDeniedHandler(new AccessDeniedHandlerImpl())
            );
            // 构建并返回过滤链
            SecurityFilterChain filterChain = http.build();
            logger.info("WebSecurityConfig loaded successfully.");
            return filterChain;
        } catch (Exception e) {
            logger.error("Error occurred while building SecurityFilterChain: {}", e.getMessage(), e);
            throw e; // 重新抛出异常以便Spring能够感知
        }
    }

    /**
     * 配置授权规则
     */
    private void configureAuthorization(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorizeRequests ->
                authorizeRequests
                        // 跳过对这些路径的拦截（严格匹配路径）
                        .requestMatchers("/resources/**",
                                "/login",
                                "/api/user/register",
//                                "/api/sms/**",
                                "/api/auth/**"
                        ).permitAll()
                        // 跳过OpenAPI相关路径（严格匹配路径）
                        .requestMatchers("/v3/api-docs/**",
                                "/swagger-ui/**").permitAll()
                        // 其他所有请求都需要认证
                        .anyRequest().authenticated()
        );
    }

    /**
     * 配置登录和登出规则
     */
    private void configureLoginAndLogout(HttpSecurity http) throws Exception {
        //禁用默认跳转登陆页面
        http.formLogin(AbstractHttpConfigurer::disable
                // 登出操作无需认证
        ).logout(LogoutConfigurer::permitAll);
    }

}
